package com.kavian.blog.dao;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.kavian.blog.domain.WPPost;
import com.kavian.test.db.DBUtil;

/**
 * 持久层
 * 
 * @author kavian
 * 
 */
public class BlogDao {

	public BlogDao() {
	}

	/**
	 * 是否存在数据
	 * 
	 * @param title
	 *            标题
	 * @return
	 */
	public WPPost findWPPostByTitle(String title) {
		try {
			DBUtil dbUtil = new DBUtil();
			String sql = "SELECT post_title FROM wp_posts WHERE post_title = '"
					+ title + "'";

			ResultSet rs = dbUtil.sendQuery(sql);
			List<WPPost> list = new ArrayList<WPPost>();
			if (null != rs) {
				WPPost wp;
				while (rs.next()) {
					wp = new WPPost();
					wp.setTitle(rs.getString("post_title"));

					list.add(wp);
				}
			}

			if (null != list && list.size() > 0) {
				return list.get(0);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取最大ID
	 * 
	 * @return
	 */
	public int findMaxId() {
		try {
			DBUtil dbUtil = new DBUtil();
			String sql = "SELECT MAX(id) FROM wp_posts";

			ResultSet rs = dbUtil.sendQuery(sql);
			rs.next();
			int max = rs.getInt(1);

			return max;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 保存对象
	 * 
	 * @param wp
	 *            对象bean
	 */
	public void saveWPPost(WPPost wp) {
		try {
			DBUtil dbUtil = new DBUtil();
			String sql = "INSERT INTO wp_posts(id,post_author,post_date,post_date_gmt,post_content,post_title,post_excerpt,post_name,to_ping,pinged,post_modified,post_modified_gmt,post_content_filtered,guid) VALUES("
					+ wp.getId()
					+ ",1,NOW(),NOW(),'"
					+ wp.getContent()
					+ "','"
					+ wp.getTitle()
					+ "','','"
					+ wp.getTitle()
					+ "','','',NOW(),NOW(),'','http://www.pcw8510.com/?p="
					+ wp.getId() + "')";

			dbUtil.sendUpdate(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 对应关系表
	 * 
	 * @param id
	 *            文章ID
	 * @param key
	 *            分类ID
	 */
	public void saveTermRelationships(int id, Integer key) {
		try {
			DBUtil dbUtil = new DBUtil();
			String sql = "INSERT INTO wp_term_relationships(object_id,term_taxonomy_id) VALUES("
					+ id + "," + key + ")";
			dbUtil.sendUpdate(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 插入meta信息
	 * 
	 * @param wp
	 *            对象bean
	 */
	public void savePostMeta(WPPost wp) {
		try {
			DBUtil dbUtil = new DBUtil();
			String sql = "INSERT INTO wp_postmeta(post_id,meta_key,meta_value) VALUES("
					+ wp.getId()
					+ ",'suf_meta_description','"
					+ wp.getDescription() + "')";
			dbUtil.sendUpdate(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}